<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

//-- ----------------------------
//--  Table structure for `sms_code`
//                        -- ----------------------------
//DROP TABLE IF EXISTS `sms_code`;
//CREATE TABLE `sms_code` (
//`id` int(6) NOT NULL AUTO_INCREMENT,
//  `code` char(6) NOT NULL COMMENT '验证码',
//  `verify_time` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT '验证时间',
//  `phone` char(14) NOT NULL COMMENT '手机号码',
//  `client_ip` char(15) NOT NULL COMMENT '发送ip地址',
//  `type` int(11) NOT NULL DEFAULT '0' COMMENT '类型 0默认 ',
//  `status` int(11) NOT NULL DEFAULT '0' COMMENT '使用状态, 0未使用 1使用 2失效',
//  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
//  `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
//  `deleted_at` timestamp NULL DEFAULT NULL,
//  PRIMARY KEY (`id`)
//) ENGINE=InnoDB DEFAULT CHARSET=utf8;

class SmsCode extends Model
{

    use SoftDeletes;

    protected $table = 'sms_code';
    protected $dates = ['deleted_at'];
    protected $fillable = ['code', 'phone', 'client_ip', 'type', 'status', 'verify_time'];

    //同一手机号一天最多发送次数
    const phoneMax = 10;

    //同一ip,一天最多的发送次数
    const ipMax = 50;

    //发送验证码在到期时间内,不重新生成验证码,防止用户没收到,点击重发又收到短信了
    const expireTime = 300;
    //验证码验证实效,十分钟内有效
    const checkExpireTime = 600;

    public function getVerifyCode($phone, $ip, $type = 0)
    {

        $count = self::where('type', $type)->where('phone', $phone)->where('created_at', '>=', date("Y-m-d"))->count();
        //同一个手机号超过每天发送的条数
        if($count >= self::phoneMax)
        {
            return false;
        }

        $count = self::where('type', $type)->where('client_ip', $ip)->where('created_at', '>=', date("Y-m-d"))->count();

        //同一个ip超过每天发送的条数
        if($count >= self::ipMax)
        {
            return false;
        }


        $lastNode = self::where('type', $type)->where('phone', $phone)->where('status', 0)->orderby('id', 'desc')->first();
        //是否修改验证码
        if(!empty($lastNode))
        {
            $lastModify = strtotime($lastNode->attributes['created_at']);

            if( (time() - $lastModify) <= self::expireTime )
            {
                $code = $lastNode->attributes['code'];
            }
        }

        $atr = [
            'code' => empty($code)? $this->_random() : $code,
            'phone' => $phone,
            'client_ip' => $ip,
            'type' => $type,
        ];

        $node = new SmsCode();
        $node->fill($atr);

        if($node->save())
        {
            return $atr['code'];
        }

        return false;
    }


    public static function checkVerifyCode($phone, $code, $type = 0)
    {
        //测试号码
        if(in_array($phone, ['13811849645', '15510073020']))
        {
            return true;
        }

        if(env('APP_ENV') != 'pro')
        {
            return true;
        }
        $node = self::where('type', $type)->where('phone', $phone)->where('status', 0)->where('code', $code)->orderby('id', 'desc')->first();

        if(empty($node))
        {
            return false;
        }

        //验证码过期
        if((time() - strtotime($node->attributes['created_at'])) > self::checkExpireTime)
        {
            $node->verify_time = date("Y-m-d H:i:s");
            $node->status = 2;
            $node->save();

            return false;
        }

        $node->verify_time = date("Y-m-d H:i:s");
        $node->status = 1;

        return $node->save();

    }
    private function _random() {
        return rand(1000, 9999);
    }

}
